/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.sentry.protocol;

import java.util.UUID;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * SentryId
 *
 * @since 2021-06-02
 */
public final class SentryId {
    /**
     * EMPTY_ID
     */
    public static final SentryId EMPTY_ID = new SentryId(new UUID(0, 0));

    private final @NotNull UUID uuid;

    /**
     * constructor
     */
    public SentryId() {
        this((UUID) null);
    }

    /**
     * constructor
     *
     * @param uuid uuid
     */
    public SentryId(@Nullable UUID uuid) {
        UUID uuid2 = uuid;
        if (uuid == null) {
            uuid2 = UUID.randomUUID();
        }
        this.uuid = uuid2;
    }

    /**
     * constructor
     *
     * @param sentryIdString sentryIdString
     */
    public SentryId(final @NotNull String sentryIdString) {
        this.uuid = fromStringSentryId(sentryIdString);
    }

    @Override
    public String toString() {
        return uuid.toString().replace(getMiddleLine(), "");
    }

    @NotNull
    private String getMiddleLine() {
        return "-";
    }

    @Override
    public boolean equals(final @Nullable Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }
        SentryId sentryId = (SentryId) obj;
        return uuid.compareTo(sentryId.uuid) == 0;
    }

    @Override
    public int hashCode() {
        return uuid.hashCode();
    }

    private @NotNull UUID fromStringSentryId(@NotNull String sentryIdString) {
        String sentryIdString2 = sentryIdString;
        if (sentryIdString2.length() == 32) {
            sentryIdString2 =
                new StringBuilder(sentryIdString2)
                    .insert(8, getMiddleLine())
                    .insert(13, getMiddleLine())
                    .insert(18, getMiddleLine())
                    .insert(23, getMiddleLine())
                    .toString();
        }
        if (sentryIdString2.length() != 36) {
            throw new IllegalArgumentException(
                "String representation of SentryId has either 32 (UUID no dashes) "
                    + "or 36 characters long (completed UUID). Received: "
                    + sentryIdString2);
        }

        return UUID.fromString(sentryIdString2);
    }
}
